package cn.e_eap.esite.manager.impl;

import cn.e_eap.esite.bean.Employee;
import cn.e_eap.esite.manager.BaseManager;
import cn.e_eap.esite.manager.EmployeeManager;
import cn.e_eap.esite.util.ApplicationException;
import cn.e_eap.esite.web.form.PagerForm;
import java.util.List;
import org.springframework.stereotype.Component;

@Component("empManager")
public class EmployeeManagerImpl extends BaseManager<Employee> implements
		EmployeeManager {

	@Override
	public void add(Employee emp) {
		if(emp.getEmpId()==null || emp.getEmpId().length()==0){
			throw new ApplicationException("employee id could not be null");
		}
		
		Employee emp2 = findByEmpId(emp.getEmpId());
		if(emp2 !=null) {
                throw new ApplicationException("employee id " + emp.getEmpId()+" already exists!");
            }
		getHibernateTemplate().save(emp);
	}

	@Override
	public void delete(String ids) {
		super.removeByIds(Employee.class, ids);
	}

	@Override
	public void update(Employee emp) {
		getHibernateTemplate().update(emp);
	}

	@Override
	public Employee findById(int id) {
		return getHibernateTemplate().get(Employee.class, id);
	}

	@Override
	public List<Employee> find(Employee condition, PagerForm pf) {
		if (condition == null ) {
			return super.getPageModel(Employee.class, pf) ;
		}

		StringBuilder hql = new StringBuilder();

		if (condition.getDept() != null && condition.getDept().length()>0) {
			hql.append(" and @.dept like '%").append(condition.getDept()).append("%'");
		}
		if (condition.getType() != null &&  condition.getType().length()>0 ) {
			hql.append(" and @.type like '%").append(condition.getType()).append("%'");
		}
		if (condition.getRealName() != null) {
			hql.append(" and @.realName like '%").append(condition.getRealName()).append("%'");
		}
		
		if (condition.getEmpId() != null && condition.getEmpId().length()>0) {
			hql.append(" and @.empId like '%").append(condition.getEmpId()).append("%'");
		}
		
		return super.getPageModel(Employee.class, hql.toString(),
				pf);
	}

	@Override
	public Employee findByEmpId(String empId) {
		return super.findUnique(Employee.class, " where @.empId='" + empId+"'");
	}

}
